﻿@using WishlistUtilities;
@using System.Text.RegularExpressions;

<h1>Edit Item</h1>

@{
	PageData["Title"] = "Edit Item";

	WebSecurity.RequireAuthenticatedUser();

	if (!Request["itemId"].IsInt() || (Request["returnUrl"] == null)) {
		Response.Redirect("~/Shared/Errors/Error");
	}

	var itemId = Request["itemId"].AsInt();
	var returnUrl = Request["returnUrl"];

	var db = Database.Open("wishlistdb");

	var itemToEdit = db.QuerySingle("SELECT * FROM Item, List WHERE Item.ListId = List.Id AND List.WishlistUserId = @0 AND Item.Id = @1",
		WebSecurity.CurrentUserId, itemId);

	if (itemToEdit == null) {
		// either not the item owner, or bad item id value
		Response.Redirect("~/Shared/Errors/Error");
	}

    var errorMessage = "";

	if (IsPost) {
		if (Request["action"] == "Cancel") {
			Context.RedirectLocal(returnUrl);
		}

		if (Request["action"] == "Update") {
			var newName = Request["newName"];
			var newPrice = Request["newPrice"];
			var newLink = Request["newLink"];
			var newClaimed = (Request["newClaimed"] == null) ? "false" : "true";	// need to do a null check since this is a value
																					// from a checkbox and if it's not set, the value is null

			if (newName.IsEmpty()) {
				errorMessage += "<li>Item name is required.</li>";
			}

			if (newLink.IsEmpty()) {
				errorMessage += "<li>Link is required.</li>";
			} else {
				if (!ValidationUtility.IsValidUrl(newLink)) {
					errorMessage += "<li>Link is invalid.</li>";
				}
			}

			if (!newPrice.IsDecimal() || (newPrice.AsDecimal() < 0)) {
				errorMessage += "<li>A valid price is required.</li>";
			}

			if (errorMessage.IsEmpty()) {
				try {
					db.Execute("UPDATE Item SET Name = @1, Link = @2, Price = @3, Claimed = @4 WHERE Id = @0", 
						itemId, newName, newLink, newPrice, newClaimed);
				} catch (Exception) {
					Response.Redirect("~/Shared/Errors/Error");
				}

				Context.RedirectLocal(returnUrl);
			}
		}
	}

    if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
}

<div id="editItem">
	<span>
		<form id="validateForm" method="post" action="">
			<fieldset>
				@RenderPage("~/Shared/_PrePopInputFormField.cshtml",
					new { labelName = "newName", labelDisplay = "Name:", inputValue = itemToEdit.Name, maxLength = 100, required = true})
				@RenderPage("~/Shared/_PrePopInputFormField.cshtml",
					new { labelName = "newPrice", labelDisplay = "Price:", inputValue = itemToEdit.Price, required = true, 
						validationClasses = "number", validationAttributes = "min=\"0\""})
				@RenderPage("~/Shared/_PrePopInputFormField.cshtml",
					new { labelName = "newLink", labelDisplay = "Link:", inputValue = itemToEdit.Link, required = true,
						validationClasses = "url"})
				@RenderPage("~/Shared/_PrePopInputFormField.cshtml",
					new { labelName = "newClaimed", labelDisplay = "Item claimed:", inputValue = itemToEdit.Claimed.ToString(), 
						inputType = "checkbox", required = true})
				<input name="itemId" type="hidden" value="@itemId" />
				<input name="returnUrl" type="hidden" value="@returnUrl" />
				<div class="submit-group">
					<input name="action" type="submit" value="Update" onclick="javascript:$('#validateForm').validate()" />
					<input name="action" type="submit" value="Cancel" class="cancel" />
				</div>
			</fieldset>
		</form>
	</span>
</div>